//
// Created by jie.jiang on 2022/12/8.
//

#include "time_utils.h"
#include "stdint.h"
#include "stm32f1xx.h"

#define SYSTEM_CORE_CLOCK    72000000     //Cortex-M3 Frequency

void DWT_Init(void)
{
  DEM_CR         |= (unsigned int)DEM_CR_TRCENA;   /* Enable Cortex-M4's DWT CYCCNT reg.  */
  DWT_CYCCNT      = (unsigned int)0u;
  DWT_CR         |= (unsigned int)DWT_CR_CYCCNTENA;
}

void delay_ms(uint32_t _ulDelayTime)
{
  delay_us(1000*_ulDelayTime);
}

void delay_us(uint32_t _ulDelayTime)
{
  uint32_t tCnt, tDelayCnt;
  uint32_t tStart;

  tStart = DWT_CYCCNT;                                     /* 刚进入时的计数器值 */
  tCnt = 0;
  tDelayCnt = _ulDelayTime * (SYSTEM_CORE_CLOCK / 1000000);	 /* 需要的节拍数 */

  while(tCnt < tDelayCnt)
  {
    tCnt = DWT_CYCCNT - tStart; /* 求减过程中，如果发生第一次32位计数器重新计数，依然可以正确计算 */
  }
}